package multiagent

import (
	"anders-cli/internal/ai"
	"fmt"
	"strings"
	"time"
)

// Architect 系统架构师Agent
type Architect struct {
	*BaseAgent
}

// NewArchitect 创建架构师
func NewArchitect(backend ai.Backend) *Architect {
	return &Architect{
		BaseAgent: &BaseAgent{
			Name:        "Architect",
			Role:        "System Architect",
			Backend:     backend,
			TaskCounter: 0,
		},
	}
}

// NewArchitectWithRules 创建带有角色规则的架构师
func NewArchitectWithRules(characterName string, backend ai.Backend) (*Architect, error) {
	baseAgent, err := NewBaseAgentWithRules("Architect", "architect", characterName, backend)
	if err != nil {
		return nil, err
	}

	return &Architect{
		BaseAgent: baseAgent,
	}, nil
}

// Process 处理架构设计任务
func (ar *Architect) Process(task string, context map[string]any) (output string, confidence int, feedback string) {
	// 初始化日志以防nil指针
	ar.initLog()

	// 使用角色规则构建基础提示
	basePrompt := ar.RulesContent
	if basePrompt == "" {
		basePrompt = fmt.Sprintf("You are %s, a System Architect. Design technical architecture and provide implementation guidance.", ar.Name)
	}

	prompt := fmt.Sprintf(`%s

Task: %s

Please provide:
1. High-Level System Architecture
2. Technology Stack Recommendations
3. Component Design and Interactions
4. Scalability and Performance Considerations
5. Security Architecture
6. Deployment Strategy

Focus on technical feasibility and best practices.`, basePrompt, task)

	output, err := ar.Backend.Query(prompt, nil)
	if err != nil {
		return fmt.Sprintf("Architecture design failed: %v", err), 20, "Technical error in design"
	}

	// 评估置信度
	confidence = ar.evaluateConfidence(output, task)

	// 生成反馈
	feedback = ar.generateFeedback(output, confidence)

	// 更新任务日志
	ar.CurrentLog = &TaskLog{
		TaskID:        ar.generateTaskID(),
		Description:   "Technical architecture design",
		InputSummary:  fmt.Sprintf("Task: %s", task[:min(50, len(task))]),
		OutputSummary: output[:min(100, len(output))],
		Status:        "completed",
		Confidence:    confidence,
		Feedback:      feedback,
		Timestamp:     time.Now().Unix(),
	}

	return output, confidence, feedback
}

// evaluateConfidence 评估架构设计的置信度
func (ar *Architect) evaluateConfidence(output, task string) int {
	confidence := 75 // 基础置信度

	// 检查是否包含关键架构元素
	archIndicators := []string{"architecture", "components", "scalability", "security", "deployment"}
	matchedIndicators := 0

	for _, indicator := range archIndicators {
		if strings.Contains(strings.ToLower(output), indicator) {
			matchedIndicators++
		}
	}

	confidence += matchedIndicators * 4

	// 检查技术深度
	techTerms := []string{"microservices", "api", "database", "cloud", "container"}
	techMatches := 0
	for _, term := range techTerms {
		if strings.Contains(strings.ToLower(output), term) {
			techMatches++
		}
	}

	if techMatches > 2 {
		confidence += 10
	}

	if confidence > 95 {
		confidence = 95
	}
	if confidence < 40 {
		confidence = 40
	}

	return confidence
}

// generateFeedback 生成架构反馈
func (ar *Architect) generateFeedback(output string, confidence int) string {
	if confidence >= 85 {
		return "Architecture design completed with comprehensive technical coverage"
	} else if confidence >= 70 {
		return "Architecture design completed with good technical foundation"
	} else {
		return "Architecture design may need additional technical details"
	}
}
